﻿#region Usings

using System;
using System.Collections.Specialized;
using System.Globalization;
using System.Reflection;

#endregion

namespace Kazkommertsbank.Framework.Common
{
    public abstract class RequestFormWrapper
    {
        protected RequestFormWrapper() : this(CultureInfo.InvariantCulture)
        {}

        protected RequestFormWrapper(CultureInfo culture)
        {
            Culture = culture;
        }

        protected RequestFormWrapper(NameValueCollection requestForm) : this(requestForm, CultureInfo.InvariantCulture)
        {}

        protected RequestFormWrapper(NameValueCollection requestForm, CultureInfo culture)
        {
            Culture = culture;
            LoadRequestForm(requestForm);
        }

        public CultureInfo Culture { get; set; }

        public void LoadRequestForm(NameValueCollection requestForm)
        {
            foreach(PropertyInfo info in GetType().GetProperties())
            {
                string strValue = requestForm[info.Name];
                if(string.IsNullOrEmpty(strValue))
                    continue;
                object value = null;
                try
                {
                    string name = info.PropertyType.Name;
                    if(!string.IsNullOrEmpty(name))
                    {
                        switch(name)
                        {
                            case "String":
                                value = strValue;
                                break;
                            case "Int32":
                                value = Convert.ToInt32(strValue);
                                break;

                            case "Boolean":
                                value = Convert.ToBoolean(strValue);
                                break;

                            case "Decimal":
                                value = Convert.ToDecimal(strValue, Culture);
                                break;
                            default:
                                value = strValue;
                                break;
                        }
                    }
                    if(value != null)
                        info.SetValue(this, value, null);
                }
                catch
                {}
            }
        }
    }
}